package mysql

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
	log "maya-service/collector/logger"
	"maya-service/config"
	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/utils"
)

var Question = &question{}

type question struct{}

func init() {
	Register(Question)
}

func (a *question) Init() {
	if config.Conf.AutoMigrate {
		p := &entity.Question{}
		if db.Migrator().HasTable(p) {
			log.Debug("table already exist: ", zap.String("table", p.TableName()))
			return
		}
		if err := db.AutoMigrate(p); err != nil {
			log.Error("filed to create table please check config or manually create", zap.String("table", p.TableName()), zap.String("err", err.Error()))
		} else {
			log.Info("create table successfully", zap.String("table", p.TableName()))
		}
	}
}

// Create
func (a *question) Create(ctx context.Context, m *entity.Question) (int64, error) {
	err := GetDB(ctx).Create(m).Error
	return m.Id, err
}

// Find detail
func (a *question) Find(ctx context.Context, in *model.QuestionInfoRequest) (*entity.Question, error) {
	e := &entity.Question{}

	q := GetDB(ctx).Model(&entity.Question{})

	count := 0
	if in.Id > 0 {
		q = q.Where("id = ?", in.Id)
		count++
	}

	if in.Name != "" {
		q = q.Where("title = ?", in.Name)
		count++
	}

	if in.LevelId > 0 {
		q = q.Where("level_id = ?", in.LevelId)
		count++
	}

	if count == 0 {
		return e, nil
	}
	err := q.First(&e).Error
	return e, err
}

// Update
func (a *question) Update(ctx context.Context, id int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.Question{}).Where("id = ?", id).Updates(dict).Error
}

// Delete
func (a *question) Delete(ctx context.Context, in *model.QuestionDeleteRequest) error {
	if in.Id > 0 {
		return GetDB(ctx).Delete(&entity.Question{}, in.Id).Error
	}

	if len(in.Ids) > 0 {
		return GetDB(ctx).Where("id in ?", in.Ids).Delete(&entity.Question{}).Error
	}

	if in.LevelId > 0 {
		return GetDB(ctx).Where("level_id = ?", in.LevelId).Delete(&entity.Question{}).Error
	}

	return fmt.Errorf("condition illegal")
}

// List query list
func (a *question) List(ctx context.Context, in *model.QuestionListRequest) (int, []*entity.Question, error) {
	var (
		q         = GetDB(ctx).Model(&entity.Question{})
		err       error
		total     int64
		questions []*entity.Question
	)

	if in.Title != nil {

		q = q.Where("title like ?", utils.SqlLike(in.Title))

	}

	if in.Type != nil {

		q = q.Where("`type` = ?", in.Type)

	}

	if in.AnswerId != nil {

		q = q.Where("answer_id = ?", in.AnswerId)

	}

	if in.LevelId != nil {

		q = q.Where("level_id = ?", in.LevelId)

	}

	if in.CreatedAt != nil {

		q = q.Where("created_at = ?", in.CreatedAt)

	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

	}

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Order("created_at desc").Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&questions).Error; err != nil {
		return 0, nil, err
	}
	return int(total), questions, nil
}

// ExecTransaction execute database transaction
func (a *question) ExecTransaction(ctx context.Context, callback func(ctx context.Context) error) error {
	return GetDB(ctx).Transaction(func(tx *gorm.DB) error {
		ctx = context.WithValue(ctx, ContextTxKey, tx)
		return callback(ctx)
	})
}
